/**
 * Created by IntelliJ IDEA.
 * User: ryan
 * Date: Sep 15, 2010
 * Time: 1:57:45 PM
 * To change this template use File | Settings | File Templates.
 */
var meeting = meeting || {};

meeting.toMeeting = function(doc, db) {
    var result = {};
    result.startDate = this.getStartDate(doc);
    result.readableStartDate = this.getReadableDate(result.startDate);

    result.endDate = this.getEndDate(doc);
    if (result.endDate) {
        result.readableEndDate = this.getReadableDate(result.result.endDate);
    }

    return result;
}

meeting.getStartDate = function(doc) {
    if (doc['-Recording'] && doc['-Recording']['-startDate']) {
        return new Date (doc['-Recording']['-startDate']);
    }
}


meeting.getReadableDate = function(date) {
        return date.toString('d MMMM yyyy, h:ss tt');
}

meeting.getEndDate = function(doc) {
    if (doc['-Recording'] && doc['-Recording']['-endDime']) {
        return new Date (doc['-Recording']['-endDime']);
    }
}

meeting.ui = meeting.ui || {};


meeting.ui.form = $('<form id="currentForm">')
            .css('margin-left', '0px')
            .append('<input type="text" id="entry" name="entry" tabindex="1"/>')
            .append('<div class="indentHelper"><img class="blur" src="images/actions/light.grey.1leftarrow.png" alt="Leave  return to" title="Leave  return to " /></div>');


meeting.ui.currentDiv = null;
meeting.ui.context = {
        topicStack:[],
        recording: 'recording1'

    }

meeting.ui.lastTopic = null;
meeting.ui.idGen = 0;
meeting.ui.mainPanel;

meeting.ui.createMeeting = function(div, minutes, db, conversation) {
    div = $(div);



    div.empty(); // prepare the div. clear anything there
    //div.css('padding-bottom', '70px');
    var mainPanel = $('<div class="minuteHolder"></div>');
    div.append(mainPanel);
    div = mainPanel;
    meeting.ui.mainPanel = div;

    meeting.ui.context.conversation = conversation;


    var flyout = $('<div id="topicInfoFlyoutPane"></div>').css({
        position: 'absolute',
        width: '200px',
        border: '1px solid #DAE3E9',
        'z-index': 100,
        'background-color' : 'white'
    });
    flyout.hide();
    $('body').append(flyout);

    $.each(minutes, function(i, minute) {
       var topicChange = meeting.ui.appendMinute(minute, div);
       if (topicChange) {
           meeting.ui.lastTopic = minute;
       }
    });
    if (meeting.ui.lastTopic != null) {
        meeting.ui.setActiveTopic(meeting.ui.lastTopic);
    } else {
        meeting.ui.form.appendTo(div);
        var currentFlyoutTimer;
        $('#entry').autocomplete({
            minLength: 2,
            delay: 500,
            source: function(request, response) {
                var term = request.term;
                if (term.indexOf('#') != 0) {
                    //response([]);
                    return;
                }
                term = term.substring(1).toLowerCase();
                var matches = db.view("system/topics", {
                    startkey: term,
                    endkey: term + 'zzz',
                    limit: 10
                });
                response(_.map(matches.rows, function(row) { return '#' + row.id }));
            },
            focus: function(event, ui) {
                ;
                if (currentFlyoutTimer) {
                    clearTimeout(currentFlyoutTimer);
                }
                flyout.text('').position({
                        of: $('#entry'),
                        my: 'left top',
                        at: 'right bottom',
                        collision: 'none'
                    })
                var topicID = ui.item.value.substring(1);
                var delayInfo = function() {
                    var doc = db.open(topicID);
                    if (doc['-wiki'] && doc['-wiki'].type && doc['-wiki'].type == 'xhtml'){
                        flyout.html(doc['-wiki'].text);
                    }
                    else if (doc['-wiki']) {
                        flyout.text(doc['-wiki']);
                    }

                    flyout.show();
                };
                currentFlyoutTimer = setTimeout(delayInfo, 100);
            },
            close: function(event, ui) {
                flyout.hide();
            }
        }).bind('autocompleteclose keyup', function(e) {
            if (e && (e.keyCode != 13 && e.keyCode != 0))  return;
            $('#currentForm').submit();
        });
        
        $('#entry').focus();
        $('.indentHelper .blur').hide();
    }



    //var subtopic = $('<div class="createSubtopic"><img class="blur" title="Start New Topic" alt="Start New Topic" src="images/actions/light.grey.list-add.png"></div>');
    //div.parent().append(subtopic);





    meeting.ui.currentDiv = div;
    // the submit will trigger the line shark


    var lessIndent = function() {
       meeting.ui.context.topicStack.pop();
       meeting.ui.currentDiv.children('.createSubtopic').remove();
       var target = meeting.ui.currentDiv.parent();
       var minute = target.data('minute');
       if (minute) {
           meeting.ui.setActiveTopic(minute);
           $('.indentHelper .blur').attr('src', lastBlurSource);
       } else {
           meeting.ui.currentDiv = div;
           meeting.ui.form.appendTo(div);
           $('.indentHelper .blur').hide();

       }
        $('#entry').focus();
    }

    shortcut.add('Ctrl+Left', function() {
        lessIndent();
        $('#entry').val('').focus();
        return false;
    });
    // open the current topic in a new window..
    shortcut.add('Ctrl+o', function() {
        var topic = $('#currentForm').parent().children('a.topic');
        if (topic && topic[0]) {
            var event = document.createEvent("HTMLEvents");
            event.initEvent("click", true, true);
            topic[0].dispatchEvent(event);

        }
        return false;
    });

    $('#currentForm').live('submit', function() {
        try {
            var val = $('#entry').val();
            if (val == '<') {
                lessIndent();
                $('#entry').val('').focus();
                return false;
            }
            var minute = lineShark.eatLine(val, meeting.ui.context);
            minute._id = 'minute' + meeting.ui.idGen++;

            meeting.ui.addMinute(minute);
        } catch (err){}
        return false;
    });


    // handle the indentHelper click
    $('.indentHelper').live('click', function() {
        lessIndent();
    });




    /** All items with blur as a class will have a 'focus' effect on mouse over */
    var lastBlurSource;
    $('.blur')
        .live('mouseover', function() {
            lastBlurSource = $(this).attr('src');
            var src = lastBlurSource.replace("light.", "");
            $(this).attr('src', src);
        })
        .live('mouseout', function() {
            $(this).attr('src', lastBlurSource);
        });
}

/**
 * Call this as opposed to append. this does some ground work
 * @param minute the minute to add
 */
meeting.ui.addMinute = function(minute) {
    var isTopicChange  = meeting.ui.appendMinute(minute,  meeting.ui.currentDiv);

    if (isTopicChange) {
        meeting.ui.context.topicStack.push(minute.topic);
        meeting.ui.lastTopic = minute;
        meeting.ui.setActiveTopic(meeting.ui.lastTopic);
    } else {
        meeting.ui.form.appendTo( meeting.ui.currentDiv);
    }
    /** ********************** We need some way to do this!!! ***********************/
    //div.parent().parent().scrollTo('max');
    meeting.ui.mainPanel.parent().parent().scrollTo('max');
    

    $('#entry').val('').focus();
    meeting.ui.currentDiv.children('.createSubtopic').appendTo( meeting.ui.currentDiv);
}



/**
 * Appends the minute to the div, decides what type of div it is.
 * @param minute
 * @param div
 * returns true if it was a topicChange
 */
meeting.ui.appendMinute = function(minute, div) {
    if (minute.type == 'topicChange') {
        var box  =  meeting.ui.createTopicBox(minute);
        if (minute.parent) {
            var divToUse = $('#' + minute.parent);
            divToUse.append(box);
            divToUse.children('.createSubtopic').appendTo( divToUse);
        } else {
            div.append(box);
            div.children('.createSubtopic').appendTo( div);
        }
        // set the topic for this div
        box.data('minute', minute);

        $('.indentHelper .blur').show();
        return true;

    }
    if (minute.type == 'reference') {
        var entry = meeting.ui.createReference(minute);
        if (minute.parent) {
            $('#' + minute.parent).append(entry);
        } else {
            div.append(entry);
        }
        return false;
    }
}

meeting.ui.createReference = function(minute) {
    var p = $('<p>').text(minute.text);
    p.data('minute', minute);
    return p;
}

meeting.ui.createTopicBox = function(minute) {
    var level = minute.topicStack.length + 1;

    var div = $('<div id="' + minute._id + '" class="topicBox topicBox'+level+'"></div>');
    div.data('minute', minute);
    var title = $('<h2>' + meeting.ui.getTopicTitle(minute) +  '</h2>');
    div.append(title);
    if (minute.topic) {
        //div.attr('title', minute.topic);
        var href= wikid.getTagLinkJqNode(minute.topic);
        href.addClass('external').attr('target', '_blank');


        title.after(href);

    }
    return div;
}


meeting.ui.getTopicTitle = function(minute) {
    if (minute.text) return minute.text;
    else return wikid.titleFromTopicId(minute.topic);
}


meeting.ui.setActiveTopic = function(minute) {
    var current = $('#' + minute._id);

    meeting.ui.currentDiv = current;

    meeting.ui.form.appendTo(current);


    var currentTopic = wikid.titleFromTopicId(meeting.ui.currentTopic(minute));
    var previousTopic = wikid.titleFromTopicId(meeting.ui.previousTopic(minute));


    var indentHelpText  = 'Leave \''+currentTopic+'\' return to \''+previousTopic+'\'';
    //var indentHelper = $('<div class="indentHelper"><img class="blur" src="images/actions/light.grey.1leftarrow.png" alt="Leave \''+currentTopic+'\' return to \''+previousTopic+'\'" title="Leave \''+currentTopic+'\' return to \''+previousTopic+'\'" /></div>');
    //meeting.ui.form.append(indentHelper);
    $('.indentHelper img').attr('alt', indentHelpText).attr('title', indentHelpText);

    $('.createSubtopic').remove();
    // do all the subtopic buttons
    // current subtopic
    if (current.children('.createSubtopic').size() == 0) {
        var subtopic = $('<div class="createSubtopic"><img class="blur" title="Add subtopic to \''+currentTopic+'\'" alt="Add subtopic to \''+currentTopic+'\'" src="images/actions/light.grey.list-add.png"></div>');
        current.append(subtopic);
    } else {
        current.children('.createSubtopic').appendTo( current);
    }

    // all the parents
    current.parents('.topicBox').each(function(){
        var thisDiv = $(this);
        if (thisDiv.children('.createSubtopic').size() > 0) return;
        var thisMinute = thisDiv.data('minute');



        var currentTopic2 = wikid.titleFromTopicId(meeting.ui.currentTopic(thisMinute));
        var previousTopic2 = wikid.titleFromTopicId(meeting.ui.previousTopic(thisMinute));
        var subtopic2 = $('<div class="createSubtopic"><img class="blur" title="Add subtopic to \''+currentTopic2+'\'" alt="Add subtopic to \''+currentTopic2+'\'" src="images/actions/light.grey.list-add.png"></div>');
        thisDiv.append(subtopic2);

    });


    $('#entry').focus();

}

meeting.ui.currentTopic = function(minute) {
    if (minute.topic) return minute.topic;
    if (minute.topicStack && minute.topicStack.length > 0) {
        return minute.topicStack[minute.topicStack.length - 1];
    }
    return minute.conversation;
}

meeting.ui.previousTopic = function(minute) {
    if (minute.topic && (!minute.topicStack || minute.topicStack.length == 0 ||  minute.topicStack.length == 1)) {
        return wikid.titleFromTopicId(minute.conversation);
    }
    if (minute.topicStack && minute.topicStack.length > 1) {
        return minute.topicStack[minute.topicStack.length - 2];
    }

    return minute.conversation;
}





/*****************  Agenda Functions ***************************************/

/**
 * Parse text that represents and agenda.
 * @param agendaText
 * @param options
 */
meeting.parseAgenda = function(agendaText, options) {
    var agendaItems = [];
    console.log(agendaText);
    var jqNode = $(agendaText.text);
    var topicStack = [];
    var lastTopic;
    var lastDepth = {depth: null};

    jqNode.find('li').each(function() {
       var node = $(this).clone().children('ul').remove().end();
       var item = {
            _id: guid(),
            type: "topicChange",
            text: node.text()
       };
       var topicLink = node.find('a').attr('href');
       if (topicLink !== undefined) {
           var topic = topicLink.substring(1);
           item.topic = topic;
           lastTopic = topic;
       }
       else {
           lastTopic = node.text();
       }
       item.topicStack = meeting.findTopicStack($(this)); 

       agendaItems.push(item);
    });
    console.log(agendaItems);
    return agendaItems;
}


meeting.findTopicStack = function(node) {
    var topicStack = [];
    var parent = node.parent('ul').parent('li');
    while (parent.size() > 0) {
       var p_node = parent.clone().children('ul').remove().end();
       var topicLink = p_node.find('a').attr('href');
       var topic;
       if (topicLink !== undefined) {
           topic = topicLink.substring(1);
       }
       if (!topic) {
           topic = p_node.text()
       }
       topicStack.push(topic);
       parent = parent.parent('ul').parent('li');
    }
    return topicStack;
}


meeting.agendaItemsToHTML = function(agendaItems) {
    if (!_.isArray(agendaItems)) return;
    var root = $('<ul></ul>');
    var currentList = root;
    var lastDepth = 0;
    var last_li;
    $.each(agendaItems, function(i,agendaItem) {
        var span = $('<span id="'+agendaItem._id+'" class="agendaItem">'+ agendaItem.text +'</span>').data('minute', agendaItem);
        var li = $('<li></li>');       
        li.append(span);
        if (!last_li) last_li = li;
        if (agendaItem.topicStack.length > lastDepth) {
            var newList = $('<ul></ul>');
            last_li.append(newList);
            currentList = newList;
        } else if (agendaItem.topicStack.length < lastDepth) {
            currentList = currentList.parent().parent();
        }
        currentList.append(li);
        lastDepth = agendaItem.topicStack.length;
        last_li = li;



    });
    return root;
}

meeting.attendeesToHtml = function(attendees, db, div) {

    $.each(attendees, function(i, attendee) {
        var doc = db.open(attendee);
        var a_div = meeting.attendeeToHtml(attendee, doc);
        div.append(a_div);
    });

    // fix any broken images
    $('.attendee > img').error(function() {
        $(this).unbind("error").attr("src", "images/anon.jpg");
    });
}

meeting.attendeeToHtml = function(attendee, doc) {

    var readableName = wikid.titleFromTopicId(attendee);
    var div = $('<div class="attendee" title="'+readableName+'"></div>');
    var img = wikid.Person.getImage(doc);
    if (img) {
        var imgJq = $('<img src="'+img+'"></img>')
        imgJq.attr('alt', readableName);
        imgJq.attr('title', readableName);
        div.append(imgJq);
    }
    div.append('<p>'+readableName+'</p>');
    return div;
}

